package com.raising.framework.filter.realm;

import com.raising.framework.spring.SpringUtils;
import com.raising.modules.sys.entity.User;
import com.raising.modules.sys.service.UserService;
import com.raising.utils.JCacheUtils;
import com.raising.utils.PasswordUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;

import java.util.Date;

//import com.raising.system.modules.framework.sm.entity.SMCode;

/**
 * 自定义验证比较类,核心类
 * @author gaoy
 * 2017 2017-5-8 下午8:19:19
 */
public class MyCredentialsMatcher extends SimpleCredentialsMatcher {  
	private static UserService userService = SpringUtils.getBean(UserService.class);
	
	/**
	 * 错误次数统计拦截
	 * @author gaoy
	 */
	@Override  
    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {  
		String username = (String)authcToken.getPrincipal();
        //错误次数累加 10分钟后清除
        Integer retryCount = (Integer) JCacheUtils.get(JCacheUtils.PWD_RETRY_CACHE,username);
        if(retryCount == null) {
        	retryCount = 0;
        }
        if(retryCount > 5) {
            //规定时间内超出错误次数
            throw new ExcessiveAttemptsException();
        }
        //调用父类匹配方案 GY
        boolean matches = doCredentialsMatchCustom(authcToken, info);
        if(matches) {
            //匹配正确后，清除错误计数器
			JCacheUtils.remove(JCacheUtils.PWD_RETRY_CACHE,username);
        }else{
        	retryCount++;
			JCacheUtils.put(JCacheUtils.PWD_RETRY_CACHE,username, retryCount);
        }
        return matches;
    }  
	
	/**
	 * 登录校验
	 * @author gaoy
	 * 2017 2017-6-19 下午5:49:30
	 * @param authcToken
	 * @param info
	 * @return
	 */
	public boolean doCredentialsMatchCustom(AuthenticationToken authcToken,AuthenticationInfo info){
		MyUsernamePasswordToken token = (MyUsernamePasswordToken) authcToken;
		//账号
		String username = token.getUsername();
		//@author goay 清除缓存
		JCacheUtils.remove(username);
		User user = userService.getUserByUserName(username);
		//自定义判断
		PasswordUtils passwordHelper = new PasswordUtils();
		//将密码加密与系统加密后的密码校验，内容一致就返回true,不一致就返回false
		if(equals(passwordHelper.getPassword(new String(token.getPassword()),user.getSalt())
				,user.getPassword())){
			userService.updateLoginInfo(user.getId(),token.getHost(),new Date());
			return true;
		}else{
			return false;
		}
	}
	
}
